<template>
  <div class="chat-message-test">
    <div class="test-header">
      <h1>聊天消息测试</h1>
      <p>测试聊天消息的发送和接收功能</p>
    </div>

    <div class="test-content">
      <!-- 用户登录状态 -->
      <div class="user-status">
        <el-card>
          <template #header>用户状态</template>
          <div v-if="userInfo">
            <p><strong>用户ID:</strong> {{ userInfo.id }}</p>
            <p><strong>用户名:</strong> {{ userInfo.username }}</p>
            <p><strong>邮箱:</strong> {{ userInfo.email }}</p>
          </div>
          <div v-else>
            <el-button @click="testLogin" type="primary">登录测试用户</el-button>
          </div>
        </el-card>
      </div>

      <!-- 会话管理 -->
      <div class="session-management">
        <el-card>
          <template #header>会话管理</template>
          
          <div class="create-session">
            <h4>创建测试会话</h4>
            <el-form :model="sessionForm" inline>
              <el-form-item label="目标用户ID">
                <el-input v-model="sessionForm.targetUserId" placeholder="输入目标用户ID" />
              </el-form-item>
              <el-form-item label="房源ID">
                <el-input v-model="sessionForm.houseId" placeholder="输入房源ID（可选）" />
              </el-form-item>
              <el-form-item>
                <el-button @click="createTestSession" type="primary" :loading="creating">
                  创建会话
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <div class="session-list" v-if="sessions.length > 0">
            <h4>现有会话</h4>
            <div v-for="session in sessions" :key="session.sessionId" class="session-item">
              <div class="session-info">
                <span><strong>会话ID:</strong> {{ session.sessionId }}</span>
                <span><strong>用户1:</strong> {{ session.userId1 }}</span>
                <span><strong>用户2:</strong> {{ session.userId2 }}</span>
                <span><strong>房源ID:</strong> {{ session.houseId || '无' }}</span>
              </div>
              <div class="session-actions">
                <el-button @click="loadSessionMessages(session.sessionId)" size="small">
                  加载消息
                </el-button>
                <el-button @click="goToChat(session.sessionId)" size="small" type="primary">
                  进入聊天
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 消息发送测试 -->
      <div class="message-test">
        <el-card>
          <template #header>消息发送测试</template>
          
          <el-form :model="messageForm" inline>
            <el-form-item label="接收者ID">
              <el-input v-model="messageForm.receiverId" placeholder="输入接收者ID" />
            </el-form-item>
            <el-form-item label="消息内容">
              <el-input v-model="messageForm.content" placeholder="输入消息内容" style="width: 300px;" />
            </el-form-item>
            <el-form-item>
              <el-button @click="sendTestMessage" type="primary" :loading="sending">
                发送消息
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 消息历史显示 -->
      <div class="message-history">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>消息历史</span>
              <el-button @click="refreshSessions" size="small">刷新会话</el-button>
            </div>
          </template>
          
          <div v-if="currentSessionId">
            <h4>当前会话ID: {{ currentSessionId }}</h4>
            <div class="messages-list">
              <div 
                v-for="message in messages" 
                :key="message.messageId"
                class="message-item"
                :class="{ 'my-message': message.senderId === userInfo?.id }"
              >
                <div class="message-header">
                  <span class="sender">发送者: {{ message.senderId }}</span>
                  <span class="time">{{ formatTime(message.sendTime) }}</span>
                </div>
                <div class="message-content">{{ message.content }}</div>
              </div>
            </div>
          </div>
          <div v-else>
            <p>请先选择一个会话</p>
          </div>
        </el-card>
      </div>

      <!-- 测试结果 -->
      <div class="test-results">
        <el-card>
          <template #header>测试结果</template>
          <div class="results-list">
            <div 
              v-for="(result, index) in testResults" 
              :key="index"
              class="result-item"
              :class="{ success: result.success, error: !result.success }"
            >
              <div class="result-header">
                <span class="result-title">{{ result.title }}</span>
                <span class="result-time">{{ result.timestamp }}</span>
              </div>
              <div class="result-description">{{ result.description }}</div>
              <div v-if="result.data" class="result-data">
                <pre>{{ JSON.stringify(result.data, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  userLogin, 
  createChatSession, 
  getChatSessions, 
  getSessionMessages, 
  sendChatMessage 
} from '@/utils/apiService'
import { getUserInfo, saveUserToken, saveUserInfo } from '@/utils/auth'

const router = useRouter()

// 响应式数据
const userInfo = ref(null)
const sessions = ref([])
const messages = ref([])
const currentSessionId = ref(null)
const testResults = ref([])

const creating = ref(false)
const sending = ref(false)

const sessionForm = reactive({
  targetUserId: '2',
  houseId: '1'
})

const messageForm = reactive({
  receiverId: '2',
  content: '这是一条测试消息'
})

// 添加测试结果
const addTestResult = (title, description, success, data = null) => {
  testResults.value.unshift({
    title,
    description,
    success,
    data,
    timestamp: new Date().toLocaleTimeString()
  })
}

// 测试登录
const testLogin = async () => {
  try {
    const loginData = {
      email: '2102530669@qq.com',
      password: 'password123'
    }
    
    const response = await userLogin(loginData)
    
    if (response.data.code === 200 || response.data.code === '200') {
      const userData = response.data.data
      saveUserToken(userData.info)
      saveUserInfo(userData.loginUser)
      userInfo.value = userData.loginUser
      
      addTestResult('用户登录', '登录成功', true, userData.loginUser)
      ElMessage.success('登录成功')
      
      // 登录后自动加载会话
      await refreshSessions()
    } else {
      throw new Error(response.data.message || '登录失败')
    }
  } catch (error) {
    addTestResult('用户登录', `登录失败: ${error.message}`, false, error)
    ElMessage.error('登录失败')
  }
}

// 创建测试会话
const createTestSession = async () => {
  if (!userInfo.value) {
    ElMessage.warning('请先登录')
    return
  }

  creating.value = true
  try {
    const sessionData = {
      targetUserId: parseInt(sessionForm.targetUserId),
      houseId: sessionForm.houseId ? parseInt(sessionForm.houseId) : null
    }
    
    const response = await createChatSession(sessionData)
    
    if (response.data.code === 200 || response.data.code === '200') {
      addTestResult('创建会话', '会话创建成功', true, response.data.data)
      ElMessage.success('会话创建成功')
      
      // 刷新会话列表
      await refreshSessions()
    } else {
      throw new Error(response.data.message || '创建会话失败')
    }
  } catch (error) {
    addTestResult('创建会话', `创建失败: ${error.message}`, false, error)
    ElMessage.error('创建会话失败')
  } finally {
    creating.value = false
  }
}

// 刷新会话列表
const refreshSessions = async () => {
  if (!userInfo.value) return

  try {
    const response = await getChatSessions()
    
    if (response.data.code === 200 || response.data.code === '200') {
      sessions.value = response.data.data || []
      addTestResult('获取会话列表', `获取到 ${sessions.value.length} 个会话`, true, sessions.value)
    } else {
      throw new Error(response.data.message || '获取会话失败')
    }
  } catch (error) {
    addTestResult('获取会话列表', `获取失败: ${error.message}`, false, error)
    ElMessage.error('获取会话列表失败')
  }
}

// 加载会话消息
const loadSessionMessages = async (sessionId) => {
  currentSessionId.value = sessionId
  
  try {
    const response = await getSessionMessages(sessionId, { page: 1, size: 50 })
    
    if (response.data.code === 200 || response.data.code === '200') {
      messages.value = response.data.data.messages || []
      addTestResult('加载消息', `会话 ${sessionId} 加载到 ${messages.value.length} 条消息`, true, messages.value)
      ElMessage.success(`加载到 ${messages.value.length} 条消息`)
    } else {
      throw new Error(response.data.message || '加载消息失败')
    }
  } catch (error) {
    addTestResult('加载消息', `加载失败: ${error.message}`, false, error)
    ElMessage.error('加载消息失败')
  }
}

// 发送测试消息
const sendTestMessage = async () => {
  if (!userInfo.value) {
    ElMessage.warning('请先登录')
    return
  }

  sending.value = true
  try {
    const messageData = {
      receiverId: parseInt(messageForm.receiverId),
      content: messageForm.content,
      type: 1
    }
    
    const response = await sendChatMessage(messageData)
    
    if (response.data.code === 200 || response.data.code === '200') {
      addTestResult('发送消息', '消息发送成功', true, response.data.data)
      ElMessage.success('消息发送成功')
      
      // 清空输入框
      messageForm.content = ''
      
      // 如果当前有选中的会话，刷新消息
      if (currentSessionId.value) {
        await loadSessionMessages(currentSessionId.value)
      }
    } else {
      throw new Error(response.data.message || '发送消息失败')
    }
  } catch (error) {
    addTestResult('发送消息', `发送失败: ${error.message}`, false, error)
    ElMessage.error('发送消息失败')
  } finally {
    sending.value = false
  }
}

// 进入聊天页面
const goToChat = (sessionId) => {
  router.push({
    path: '/chat',
    query: {
      sessionId: sessionId,
      userId: sessionForm.targetUserId,
      userName: '测试用户'
    }
  })
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  return new Date(timeStr).toLocaleString()
}

// 页面加载时初始化
onMounted(() => {
  // 检查当前登录状态
  const currentUser = getUserInfo()
  if (currentUser) {
    userInfo.value = currentUser
    refreshSessions()
  }
})
</script>

<style scoped>
.chat-message-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-header {
  text-align: center;
  margin-bottom: 30px;
}

.test-header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.test-header p {
  color: #7f8c8d;
  font-size: 16px;
}

.test-content > div {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.session-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 10px;
}

.session-info span {
  margin-right: 15px;
}

.session-actions {
  display: flex;
  gap: 10px;
}

.messages-list {
  max-height: 400px;
  overflow-y: auto;
}

.message-item {
  padding: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 10px;
}

.message-item.my-message {
  background-color: #e3f2fd;
  border-color: #2196f3;
}

.message-header {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.message-content {
  font-size: 14px;
  color: #333;
}

.results-list {
  max-height: 300px;
  overflow-y: auto;
}

.result-item {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
}

.result-item.success {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.result-item.error {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.result-header {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  margin-bottom: 5px;
}

.result-description {
  color: #606266;
  margin-bottom: 5px;
}

.result-data pre {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 200px;
  overflow: auto;
}
</style>
